<html>
<head>
<title>A parser generator in Python</title>
</head>
<body bgcolor="#ffffff">
<center>
<h1>A parser generator in Python: kwParsing</h1>


<blockquote>
Aaron Watters<br>
</blockquote>

<blockquote>
This is the documentation for the <strong>kjParsing</strong> package,
an experimental parser generator implemented in Python which generates
parsers implemented in Python.
It won't serve as a complete reference on programming
language syntax and interpretation, but it will review
terminology for the knowledgable and I hope it will pique
the interest of the less experienced.
</blockquote>
</center>

<h2>Introduction</h2>
<p>
The <code> kjParsing</code> package is a parser generator written
in Python which generates parsers for use in Python.
<p>
These modules and their documentation and demo files
may be of use for classes on parsing, compiling, or
formal languages, and may also be helpful to people
who like to create experimental interpreters or translators
or compilers.
<p>
The package consists of three Python modules:
<code> kjParser, kjParseBuild,</code> and <code> kjSet</code>.  Together these
modules are called the <code> kjParsing</code> package.
The package also includes some documentation and demo
files and a <code> COPYRIGHT</code> file which explains the
conditions for copying and propagating this code
and the fact that the author assumes no responsibility
for any difficulties resulting from the use of this
package by anyone (including himself).

<h2>What a Parser Does</h2>

Parsers can be part of a lot of different things:
compilers, interpreters, translators, or code generators,
among others.  Nevertheless, at an abstract level parsers
all translate expressions of a language into computational
actions.
<p>
Parsers generated by the <code> kjParseBuild</code> module may do three
different sorts of actions: 
<center><table bgcolor="#ffdd66" border>
<tr><th>Value Computation</th></tr><tr><td>
The parser may build a data structure
as the result of the expression.  For example the silly <code> LispG</code>
grammar
from the file
<code> ``DLispShort.py''</code> can construct integers, strings and
lists from string representations.
<pre>
>>> from DLispShort import LispG, Context
>>> LispG.DoParse1( ' ("list with string and int" 23) ', Context)
['list with string and int', 23]
>>>
</pre>
</td></tr><tr><th>Environment Modification</th></tr><tr><td>
The parser may modify the context of the computation.  For example
the <code> LispG</code> grammar allows the assignment of values to internal
variable names.
<pre>
>>> LispG.DoParse1( '(setq Variable (4 5 9))', Context)
[4, 5, 9]
>>> Context['Variable']
[4, 5, 9]
>>>
</pre>
(Here the second result indicates that the string <code> 'Variable'</code>
has been associated with the value <code> [4,5,9]</code> in
the <code> Context</code> structure, which in this case is a simple
python dictionary.)
</td></tr><tr><th> External Side Effects</th></tr><tr><td>
The parser may also perform external actions.  For example the
<code> LispG</code> grammar has the ability to print values to the terminal.
<pre>
>>> LispG.DoParse1( '( (print Variable) (print "bye bye")  )', Context )
[4, 5, 9]
bye bye
[[4, 5, 9], 'bye bye']
>>>
</pre>
(Here the first two lines are the results of printing
and the last is the value of the expression.)
</td></tr></table></center>
More realistic parsers will perform more interesting actions,
of course.
<p>
To implement a parser using <code> kjParseBuild</code> you must
define the grammar to parse and associate each rule and terminal
of the grammar with an action which defines the
computational meaning of each language construct.
<p>
The grammar generation process consists of two phases
<center><table bgcolor="#ffdd66" border>
<tr><th>Generation</th></tr><tr><td>
During this phase you must define the syntax of the
language and function bindings that define the semantics
of the language.  When you've debugged the syntax and 
semantics you can dump the grammar object
 representing the syntax only to a grammar file which
can be reloaded without re-analyzing the language syntax.
For large grammars each regeneration may require significant
time and computational resources.
</td></tr><tr><th>Use</th></tr><tr><td>
During this phase you may load the grammar file without
re-analyzing the grammar on each use. However,
the semantics functions must still be rebound on each
load.  The reloaded grammar object augmented with interpretation
functions may be used to parse strings of the language.
</td></tr></table></center>
Note that the functions that define the semantics of the
language are must be bound in both phases.
<p>
<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
           # from file DLispShort.py (with small differences)
     ( 1)  def GrammarBuild():
     ( 2)      import kjParseBuild
     ( 3)      LispG = kjParseBuild.NullCGrammar()
     ( 4)      LispG.SetCaseSensitivity(0) 
     ( 5)      DeclareTerminals(LispG)
     ( 6)      LispG.Keywords("setq print")
     ( 7)      LispG.punct("().")
     ( 8)      LispG.Nonterms("Value ListTail")
     ( 9)      LispG.comments([LISPCOMMENTREGEX])
     (10)      LispG.Declarerules(GRAMMARSTRING)
     (11)      LispG.Compile()
               print "dumping as binary to TESTLispG.mar"
     (12)      outfile = open("TESTLispG.mar", "w")
     (13)      LispG.MarshalDump(outfile)
     (14)      outfile.close()
     (15)      BindRules(LispG)
     (16)      return LispG
</pre>
<caption>A function for building simple grammar (GrammarBuild)</caption>
</td></tr></td></tr></table></center>

<h2>Defining a Grammar</h2>

A programming language grammar is conventionally divided into
several components:
<center><table bgcolor="#ffdd66" border>
<tr><th>Keywords</th></tr><tr><td>
These are special strings that ``highlight'' a language construct.
Familiar keywords from Python and Pascal and C are ``if'', ``else'',
and ``while''.
</td></tr><tr><th>Terminals</th></tr><tr><td>
These are special patterns of characters that indicate a value
in the language.  For example many programming languages will
classify the string <code> 123</code> as an instance of the integer
nonterminal and the string <code> snark</code> (not contained in quotes)
as an instance of the nonterminal identifier or
variable.  Terminals are usually restricted to very simple
constructs like identifiers, numbers, and strings.  More complex
things (such as a ``date'' data type) might be better handled
by nonterminals and rules.
</td></tr><tr><th>Nonterminals</th></tr><tr><td>
These are ``place holders'' for language constructs of the
grammar.  They represent parts of the grammar which sometimes
expand to great size and complexity.  For instance the
C language grammar presented by Kernigan and Ritchie has
a nonterminal translationUnit which represents a
complete C language module, a nonterminal 
conditionalExpression which represents a truth valued
expression of the language.
</td></tr><tr><th>Punctuations</th></tr><tr><td>
These are special characters or strings which are recognized
as separate entities even if they aren't physically separated
from other strings by white space.  For example, most languages
would ``see'' the string <code> if0</code> as a single token
(probably an identifier) even if <code> if</code> is a keyword,
whereas <code> if(0)</code> would be recognized
the same as <code> if ( 0 )</code> because parentheses are normally
considered punctuations.  Except for the special treatment
at recognition, punctuations are similar to keywords.
</td></tr></table></center>
The syntax of a language describes how to recognize
the components of the language.  To define a language syntax using
<code> kjParseBuild</code> you must create a null compilable grammar object
to contain the grammar (in Figure GrammarBuild this
is done on line 3 using the class constructor
<code> kjParseBuild.NullCGrammar()</code>
creating the grammar object <code> LispG</code>) and define the components
of the grammar and the rules for recognizing the components.
The component definitions
and rule declarations, as well as the specification of case sensitivity
and comment patterns, are performed on lines 4 through 10 of
Figure GrammarBuild for the <code> LispG</code> grammar.

<h3>Declaring Case Sensitivity and Comments</h3>

There are two nuances to parsing not yet mentioned:
case sensitivity and comments.  
<p>
Some grammars are not
case sensitive in recognizing keywords or identifiers.
For example ANSI standard SQL (which is not
case sensitive for keywords or identifiers) recognizes
<code> Select, select, SELECT,</code> and <code> SeLect</code> all 
as the keyword <code> SELECT</code>.
To specify the case sensitivity of the grammar for keywords only use
<pre>
     GRAMMAROBJECT.SetCaseSensitivity(TrueOrFalse) 
</pre>
where <code> TrueOrFalse</code> is 0 for no case sensitivity or
1 for case sensitivity.  This must be done before
any keyword declarations for the grammar.  All other
syntax declarations may be done in any order before
the compilation of the grammar object.
In Figure GrammarBuild the <code> LispG</code> grammar object
is declared to be case insensitive on line 4.
<p>
Comments are patterns in the input string which are ignored
(or more precisely interpreted as white space) by the language.
To declare a sequence of regular expressions to be interpreted as a comment
in a grammar use
<pre>
    GRAMMAROBJECT.comments(LIST_OF_COMMENT_REGULAR_EXPR_STRINGS)
</pre>
For example, line 9 or Figure GrammarBuild declares
the constant string previously declared as
<pre>
    LISPCOMMENTREGEX = ";.*"
</pre>
to represent a comment of the grammar <code> LispG</code>.
For the syntax of regular expression strings you must look
elsewhere, but as a hint <code> ";.*"</code> represents any string
commencing with a semicolon, followed by any sequence of
characters up to, but not including, a newline.

<h3>Declaring Keywords, Punctuations, and Terminals</h3>

To declare keywords for your grammar use
<pre>
      GRAMMAROBJECT.Keywords( STRING )
</pre>
where <code> STRING</code> is a white space separated string of keywords.
Line 6 of Figure GrammarBuild declares <code> setq</code> and <code> print</code>
as keywords of <code> LispG</code>.
<p>
To declare nonterminals for your grammar, similarly, use
<pre>
      GRAMMAROBJECT.Nonterms( STRING )
</pre>
where <code> STRING</code> is a white space separated string of nonterminal
names. Line 8 of Figure GrammarBuild declares <code> Value</code>
and <code> ListTail</code> as nonterminals of the <code> LispG</code>.
<p>
Similarly, use
<pre>
      GRAMMAROBJECT.punct( STRING )
</pre>
to declare a sequence of punctuations for the grammar, except
that in this case the string must not contain any white space.
Line 7 of Figure GrammarBuild declares parentheses and dot
to be punctuations of the <code> LispG</code>.
<p>
If you have a lot of keywords, punctuations,
or nonterminals you can make many separate
calls to the appropriate declaration methods
with different strings.
<p>
These declarations will cause the grammar to recognize
the declared keyword strings (when separated from other
strings by white space or punctuations) and punctuations
as special tokens of the grammar at the lowest level of
parsing.  The parsing process derives nonterminals of the
grammar at a higher level as discussed 
below.  
<p>
A small difficulty with
<code> kjParseBuild</code> is that the strings <code> @R, ::, >>,</code>
and <code> ##</code> cannot be used as names of keywords for the
grammar because they are used to specify rule syntax
in the ``metagrammar''.  
If you need these in your grammar they may
be implemented as ``trivial'' terminals.  For example,
<center><table bgcolor="#ffdd66" border><tr><td>
  <code>    Grammar.Addterm("poundpound", "##", echo)</code>
</td></tr></table></center>
I'm unsure whether this patch is good enough.
Does anyone have any advice for me?  If this is a bad
problem for some grammar the keywords of the meta grammar
can be changed of course, but this is a hack.

<h3>Declaring Terminals</h3>

<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
        # from DLispShort.py
        def DeclareTerminals(Grammar):
   (1)      Grammar.Addterm("int", INTREGEX, intInterp)
   (2)      Grammar.Addterm("str", STRREGEX, stripQuotes)
   (3)      Grammar.Addterm("var", VARREGEX, echo)
</pre>
</td></tr>
<caption>Defining the terminals of a grammar. 
(TermDef)</caption></table></center>

<p>
Figure TermDef shows the declarations for installing
the <code> int, str,</code> and <code> var</code> terminals in the grammar.
This is given as a separate function because the declarations
define both the syntax and semantics for the terminals,
and therefore must be called both during grammar generation
and after loading the generated grammar object.
To declare a terminal for a grammar use
<pre>
      GRAMMAROBJECT.Addterm(NAMESTR, REGEXSTR, FUNCTION)
</pre>
This declaration associates both a regular expression string
<code> REGEXSTR</code>
and an interpretation function <code> FUNCTION</code> to the
terminal of the grammar named by the string <code> NAMESTR</code>.
The <code> FUNCTION</code> defines the semantics of the terminal
as describe below and the <code> REGEXSTR</code> specifies a regular
expression for recognizing the string.  For example on
line 2 of Figure TermDef the <code> var</code> terminal
is associated with the regular expression string
<pre>
      STRREGEX = '"[^\n"]*"'
</pre>
which matches any string starting with double quotes and ending
with double quotes which contains neither double quotes nor
a newline.

<h3>Declaring Rules of the Grammar</h3>


<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
# from DLispShort.py
GRAMMARSTRING ="""
       Value ::  ## indicates Value is the root nonterminal for the grammar
         @R SetqRule :: Value >> ( setq var Value )
         @R ListRule :: Value >> ( ListTail
         @R TailFull :: ListTail >> Value ListTail
         @R TailEmpty :: ListTail >> )
         @R Varrule :: Value >> var
         @R Intrule :: Value >> int
         @R Strrule :: Value >> str
         @R PrintRule :: Value >> ( print Value )
"""
</pre>
</td></tr>
<caption>A grammar definition string.</caption>
</table></center>

<p>
To declare the rules of a grammar use the simple rule
definition language which comes with <code> kjParseBuild</code>, for example
as shown in Figure GramStr.  Line 10 of 
Figure GrammarBuild uses the string defined in
Figure GramStr to associate the rules with the
grammar using
<pre>
      GRAMMAROBJECT.DeclareRules(RULE_DEFINITION_STRING)
</pre>
This declaration does not analyse the string; analysis
and syntax/semantics errors are reported by <code> *.Compile()</code>
described below.
<p>
The rule definition language allows you to identify
the root nonterminal of your grammar and specify a
sequence of named derivation rules for the 
grammar.  It also allows comments
which start with <code> ##</code> and end with a newline.
An acceptible string for the rule definition language
looks like
<center><table bgcolor="#ffdd66" border><tr><td>
RootNonterminalName <code> ::</code> NamedRule1 NamedRule2 ...
</td></tr></table></center>
Here the Root nonterminal name should be the nonterminal
that ``stands for'' any complete string of the language.
Furthermore, each named rule looks like
<center><table bgcolor="#ffdd66" border><tr><td>
<code> @R</code> NameString <code> ::</code> GoalNonterm <code> >></code> RuleBody
</td></tr></table></center>
where the name string for the rule is a string without
whitespace, the goal nonterminal is the
nonterminal that the rule derives,
and the rule body is a sequence of keywords, punctuations
and nonterminals separated by white space.
Rule names are used for mapping rules to semantic interpretations
and should be unique.
<p>
Note that punctuations for the grammar you are defining
are not punctuations for the rule definition language
(which has none), so they must be separated from
other tokens by white space.  The keyword for the rule
definition language <code> @R, ::, >></code> must also be
separated from other tokens by whitespace in the rule
definition string.
Furthermore, all
punctuations, keywords, nonterminals, and terminals
used in the rules must be declared for the grammar before
the grammar is compiled (if one isn't the compilation will
fail with an error).
<p>
As a bit of sugar you may break up the declarations of rules.
<pre>
    LispG.DeclareRules("Value::\n")
    LispG.DeclareRules("  @R SetqRule :: Value >> ( setq var Value )\n")
    LispG.DeclareRules("  @R ListRule :: Value >> ( ListTail\n")
    ...
</pre>
This might be useful for larger grammars.

<h3>A Brief Discussion of Derivations</h3>

The rules for a grammar don't really describe how to
parse a string of the language, they actually
describe how to derive a string of the 
grammar.  For this reason it is possible
to create a grammar which derives the same string
in two different ways; such grammars are termed
ambiguous.  If you try to generate a parser
for an ambiguous grammar the parse generation process will
cause the parser generation process to complain.
<p>
For a more precise definition of the derivation of a
language string from a grammar see the ``further readings''
below.  For illustrative purposes, and to help explain
how to define semantics functions, consider the following
derivation of the string
<center><table bgcolor="#ffdd66" border><tr><td>
<code> ( 123 ( setq x "this" ) )</code>
</td></tr></table></center>
using the rules declared in Figure GramStr.
<center><table bgcolor="#ffdd66" border><tr><td>
Derivation</td><td> Rule used </td></tr><tr><td>
<code> Value1 >> ( ListTail1</code> </td><td> <code> ListRule</code> </td></tr><tr><td>
<code> ListTail1 >> Value2 ListTail2</code> </td><td> <code> TailFull</code> </td></tr><tr><td>
<code> Value2 >> [int = 123]</code> </td><td> <code> Intrule</code> </td></tr><tr><td>
<code> ListTail2 >> Value3 ListTail3</code> </td><td> <code> TailFull</code> </td></tr><tr><td>
<code> Value3 >> (setq [var='x'] Value4)</code> </td><td> <code> SetqRule</code> </td></tr><tr><td>
<code> Value4 >> [string='this']</code> </td><td> <code> StrRule</code> </td></tr><tr><td>
<code> ListTail3 >> )</code> </td><td> <code> TailEmpty</code>
</td></tr></table></center>
To obtain the string derived we simply substitute the
representations derived for each of the numbered nonterminals
and terminals of the derivation as shown
in Figure Derive.
<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
(1)    Value1 
(2)    ( ListTail1                        (ListRule)
(3)    ( Value2 ListTail2                 (TailFull)
(4)    ( 123 ListTail2                    (Intrule)
(5)    ( 123 Value3 ListTail3             (TailFull)
(6)    ( 123 ( setq x Value4 ) ListTail3  (SetqRule)
(7)    ( 123 ( setq x "this" ) ListTail3  (StrRule)
(8)    ( 123 ( setq x "this" ) )          (TailEmpty)
</pre>
</td></tr>
<caption>Right-to-left derivation steps for 
<code> (123 (setq x "this"))</code>.
         (Derive) </caption>
</table></center>

<h3>Compiling the Grammar Syntax, and Storing the Compilation</h3>

Once you have defined all the keywords, comments, terminals,
nonterminals, punctuations, and rules of your grammer you
may create the datastructures needed for parsing by
compiling the grammar using
<pre>
      GRAMMAROBJECT.Compile()
</pre>
Line 11 of Figure GrammarBuild performs the compilation
for the LispG grammar.
<p>
If the compilation succeeds you may use
<pre>
      GRAMMAROBJECT.MarshalDump( OUTPUTFILE )
</pre>
to store the compiled grammar structure to a file that
may be later loaded without recompiling the grammar.
Here <code> MarshalDump</code> will create a binary ``marshalled''
representation for the grammar in the <code> OUTPUTFILE</code>.
For example line 13 of figure GrammarBuild 
marshalls a representation for <code> LispG</code> to the
file <code> TESTLispG.mar</code>.
<code> TESTLisp.GRAMMAR()</code> will 
then reconstruct the internal
structure of LispG as a grammar object and return the
grammar object as the result of the function.
<p>
Nevertheless, compilation of the grammar by itself does
not yeild a grammar that will do any useful 
parsing [Actually, it will do ``parsing'' using
default actions (implemented as a function which simply return
the list argument).]
Rules must be associated with computational actions before
useful parsing can be done.

<h2>Defining a Semantics</h2>
<p>
Two sorts of objects require semantic actions that
define their meaning: rules and terminals.
All semantic actions must be defined as Python functions
and bound in the grammar before parsing can be performed.
<p>
Before you can define the semantics of your language
in Python you better have a pretty good idea of what
the components of the language are supposed to represent,
of course.  Using your intuitive understanding of the
language you can:
<center><table bgcolor="#ffdd66" border><tr><td>
</td></tr><tr><td>
Decide what the context of the computation should be
and how it should be implemented as a Python structure.
If the process of Parsing must modify the context, then
then the context structure must be a ``mutable'' python
structure.
In the case of <code> LispG</code> the context is simply a structure
that maps ``internal'' variable names to values,
implemented as a simple Python dictionary mapping
name strings to the appropriate value.
</td></tr><tr><td>
Decide what kind of Python value each terminal of the grammar
represents.  In the case of <code> LispG</code>
<center><table bgcolor="#ffdd66" border>
<tr><th> str</th></tr><tr><td>
should represent a string value corresponding to the string
recognized (minus the surrounding quotes).
</td></tr><tr><th> int</th></tr><tr><td>
should represent an integer value corresponding to the
string recognized.
</td></tr><tr><th> var</th></tr><tr><td>
should represent the string representing the variable name
recognized (the name must be translated to a corresponding
value at a higher level since the terminal interpretation
functions don't have access to the context 
structure).
</td></tr></table></center>
</td></tr><tr><td>
Decide what kind of Python structure or value each
nonterminal represents.  In the case of the <code> LispG</code>
grammar:
<center><table bgcolor="#ffdd66" border>
</td></tr><tr><th> Value</th></tr><tr><td> 
represents a Python integer, string, or list.
</td></tr><tr><th> ListTail</th></tr><tr><td> 
represents a Python list containing the
  members of the tail of a list.
</td></tr></table></center>
</td></tr><tr><td>
Decide how each rule should derive a structure corresponding
to the Goal (left hand side) of the rule based on the
values corresponding to the terminals and nonterminals
on the right hand side of the rule.
In the case of the <code> LispG</code> grammar
(refer to Figure GramStr for rule definitions):
<center><table bgcolor="#ffdd66" border>
<tr><th> SetqRule</th></tr><tr><td>
  should return whatever the <code> Value</code> terminal in the body
  represents.
</td></tr><tr><th> ListRule</th></tr><tr><td>
  should return the list represented by the 
  <code> ListTail</code> nonterminal of the body.
</td></tr><tr><th> TailFull</th></tr><tr><td>
  should return the result of adding the value corresponding
  to the <code> Value</code> nonterminal of the list to the front
  of the list corresponding to the <code> Listtail</code> nonterminal
  of the body.
</td></tr><tr><th> Varrule</th></tr><tr><td>
  should return the value from the computational
  context that corresponds to the variable
  name represented by the <code> var</code> terminal of the body.
</td></tr><tr><th> Intrule</th></tr><tr><td>
  should return the integer corresponding to the <code> int</code>
  terminal of the body.
</td></tr><tr><th> Strrule</th></tr><tr><td>
  should return the string corresponding to the <code> str</code>
  terminal of the body.
</td></tr><tr><th> PrintRule</th></tr><tr><td>
  should return the value represented by the <code> Value</code>
  nonterminal of the body.
</td></tr></table></center>
</td></tr><tr><td>
Decide what side effects, if any, each rule should have on
the computational context or 
externally.
In the case of the <code> LispG</code> grammar:
<center><table bgcolor="#ffdd66" border>
<tr><th> SetqRule</th></tr><tr><td>
  should associate the variable name represented by <code> var</code>
  to the value represented by <code> Value</code> in the body.
</td></tr><tr><th> PrintRule</th></tr><tr><td>
  should print the value corresponding to the <code> Value</code>
  nonterminal to the screen.
</td></tr></table></center>
The other rules of <code> LispG</code>
should have no internal or external side effects.
</td></tr></table></center>
More complex languages may require much more complex contexts,
values and side effects, including
function definitions, modules, database
table accesses, user authorization
verifications, and/or file creation, among other possibilities.
<p>
Having determined the intuitive semantics of the language you
may now specify implement the semantic functions and
bind them in your grammar.

<h3>Semantics for Terminals</h3>
<p>
To define the meaning of a terminal you must create a Python
function that translates a string (which the parser has recognized
as an instance of the terminal)
into an appropriate value.
For instance, when the LispG grammar recognizes a string
<pre>
      "this is a string"
</pre>
the interpretation function should translate the recognized
string into the Python string it represents: namely,
the same string but with the double quotes stripped off.
The following ``string intepretation function'' will perform
this simple interpretation.

<pre>
        # from DLispShort.py
        def stripQuotes( str ):
            return str[1:len(str)-1]
</pre>
Similarly, when the parser recognizes a string as
an integer, the associated interpretation function
should translate the string into a Python integer.
<p>
The binding of interpretation functions to terminal
names is performed by the <code> Addterm</code> method previously
mentioned.  For example, line 2 of Figure TermDef
associates the <code> stripQuotes</code> function to the
nonterminal named <code> str</code>.  
<p>
All functions passed to
<code> Addterm</code> should take a single string argument
which represents the recognized string, and return
a value which represents the semantic interpretation
for the input string.

<h3>Semantics for Rules</h3>
<p>
The semantics of rules is more interesting since they may
have side effects and require the kind of recursive thinking
that gives most people headaches.  The semantics for rules
are specified by functions.  To perform the
semantic action associated with a rule, the ``reduction
function'' should
perform any side effects (to the computational context or
externally) and return a result value that represents
the interpretation for the nonterminal at the head of the rule.

<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
      # from DLispShort.py
      def EchoValue( list, Context ):
          return list[0]
      
      def VarValue( list, Context ):
          varName = list[0]
          if Context.has_key(varName):
             return Context[varName]
          else:
             raise NameError, "no such lisp variable in context "+varName
      
      def NilTail( list, Context ):
          return []
      
      def AddToList( list, Context ):
          return [ list[0] ] + list[1]
      
      def MakeList( list, Context ):
          return list[1]
      
      def DoSetq( list, Context):
          Context[ list[2] ] = list[3]
          return list[3]
      
      def DoPrint( list, Context ):
          print list[2]
          return list[2]
</pre>
</td></tr>
<caption>The reduction functions for the rules. (RedFun)</caption>
</table></center>



<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
        # from DLispShort.py
        def BindRules(LispG):
            LispG.Bind( "Intrule", EchoValue )
            LispG.Bind( "Strrule", EchoValue )
            LispG.Bind( "Varrule", VarValue )
            LispG.Bind( "TailEmpty", NilTail )
            LispG.Bind( "TailFull", AddToList )
            LispG.Bind( "ListRule", MakeList )
            LispG.Bind( "SetqRule", DoSetq )
            LispG.Bind( "PrintRule", DoPrint )
</pre>
</td></tr>
<caption>Binding named rules to interpretation functions. 
(ruleBind)</caption>
</table></center>

The Python functions that define the semantics of the rules of
<code> LispG</code> appear in Figure RedFun and the declarations
that bind the rule names to the functions in the grammar object
<code> LispG</code> appear in Figure ruleBind.
<p>
Each ``reduction function'' for a rule must take two arguments:
a list representing the body of the rule and a context
structure which represents the computational context of the
computation.  The list argument will have the same length
as the body of the rule, counting the keywords and punctuations
as well as the terminals and nonterminals.
<p>
For example the <code> SetqRule</code> has a body with five tokens, 
<pre>
      @R SetqRule :: Value >> ( setq var Value )
</pre>
so the
<code> DoSetq</code> function should expect the parser to deliver a
Python list argument with five elements of form
<pre>
      list = [ '(', 'SETQ', VARIABLE_NAME, VALUE_RESULT, ')' ]
</pre>
note that the ``names'' of keywords and punctuations appear
in the appropriate positions (0, 1, and 4) of the <code> list</code>
corresponding to their positions in <code> SetqRule</code>.
Furthermore, the position occupied by the terminal
<code> var</code> in <code> SetqRule</code> has been replaced by a string
representing a variable name in the <code> list</code> and the
position occupied by the nonterminal <code> Value</code> in
<code> SetqRule</code> has been replaced by a Python value.
<p>
More generally, the parser will call reduction functions for
rules with a <code> list</code> representing the ``interpreted
body of the rule'' where
<center><table bgcolor="#ffdd66" border>
<tr><th>keywords and punctuations</th></tr><tr><td>
are interpreted as themselves (i.e., their names),
except that letters will be in upper case if the grammar
is not case sensitive;
</td></tr><tr><th>terminals</th></tr><tr><td>
are interpreted as values previously returned by a call to
the appropriate terminal interpretation function; and
</td></tr><tr><th>nonterminals</th></tr><tr><td>
are interpreted as values previously returned by a
reduction function for a rule that derived this terminal.
</td></tr></table></center>
Although, the occurrence of the keyword names in the list may seem
useless, it may have its purposes.  For example,
a careful programmer might check them during debugging
to make sure the right function was bound to the right rule.
<p>
To determine how to implement the semantics of a rule
you must refer to the semantic decisions you made earlier.
For example, above we specified that the <code> setq</code> construct
should bind the variable name recieved  (<code> list[2]</code>) 
to the value (<code> list[3]</code>) in the <code> Context</code>,
and return the value (<code> list[3]</code>) 
as the result of the expression.
Translated into the more concise language of Python this is
exactly what <code> DoSetq</code> shown in Figure RedFun
does.
<p>
To bind a rule name to a (previously declared)
reduction function use
<pre>
      GRAMMAROBJECT.Bind( RULENAME, FUNCTION )
</pre>
where <code> RULENAME</code> is the string name for the rule previously
declared for the grammar <code> GRAMMAROBJECT</code> and 
<code> FUNCTION</code> is
the appropriate reduction function for the rule.
These bindings for <code> LispG</code> are shown in Figure ruleBind.

<h3>A Bit on the Parsing Process</h3>
<p>
The following is not a precise definition
of the actions of a Parser, but it may help
you understand how the parsing process
works and the order in which rules are recognized
and functions are evaluated.
<p>
<center><table bgcolor="#ffdd66" border><tr><td>
</td><td>Tokens seen S </td><td> input remaining</td><td> 
     rule R and function call </tr><tr>
<td>0</td><td><code> </code> </td><td> <code> (123 (setq x "this"))</code> </td><td>  </tr><tr>
<td>1</td><td><code> ( 123</code> </td><td> <code> (setq x "this"))</code> </td><td> Intrule </tr><tr>
<td> </td><td></td><td></td><td> <code> Value2 = EchoValue([123],C))</code> </tr><tr>
<td>2</td><td><code> ( Value2 ( setq x "this"</code> </td><td> <code> ))</code> </td><td> StrRule </tr><tr>
 <td></td><td></td><td></td><td> <code> Value4 = EchoValue(['this'],C)</code> </tr><tr>
<td>3</td><td><code> ( Value2 ( setq x Value4 )</code> </td><td> <code> )</code> </td><td> SetqRule </tr><tr> 
 <td></td><td></td><td></td><td> <code> Value3 = DoSetq(['(','SETQ','x',Value4,')'],C)</code> </tr><tr>
<td>4</td><td><code> ( Value2 Value3 )</code> </td><td> </td><td> TailEmpty </tr><tr>
 <td></td><td></td><td></td><td> <code> ListTail3 = NilTail([')'],C)</code> </tr><tr>
<td>5</td><td><code> ( Value2 Value3 ListTail3</code> </td><td> </td><td> TailFull </tr><tr>
 <td></td><td></td><td></td><td> <code> ListTail2 = AddToList([Value3,ListTail3],C)</code> </tr><tr>
<td>6</td><td><code> ( Value2 ListTail2</code> </td><td> </td><td> TailFull </tr><tr>
 <td></td><td></td><td></td><td> <code> ListTail3 = AddToList([Value2,ListTail2],C)</code> </tr><tr>
<td>7</td><td><code> ( ListTail3</code> </td><td> </td><td> ListRule </tr><tr> 
 <td></td><td></td><td></td><td> <code> Value1 = MakeList(['(',Value1],C)</code> </tr><tr>
<td>8</td><td><code> Value1</code> </td><td> </td><td> 
</td></tr>
<caption>Parsing <code> (123 (setq x "this"))</code>
         (Parse)</caption>
</table>
<em>Technically, each entry of S is tagged with the kind of token
  it represents (keyword, nonterminal, or terminal) and the name
  of the token it represents (e.g., <code> Value</code>, <code> str</code>)
  as well as the
  values shown.</em>
</center>

<p>
Figure Parse illustrates the sequence of reduction actions
performed by <code> LispG</code> when parsing the input string
<code> (123 (setq x "this"))</code>.  We can think of this parse as
``reversing'' the derivation process shown in Figure Derive
using the rule reduction functions to obtain semantic
interpretations for the nonterminals.
<p>
At the lowest level of parsing a lexical analyser
examines the unread portion of the input string tries
to match a prefix of the input string with a keyword
or a regular expression for a terminal (ignoring comments
and whitespace, except as separators).  The analyser ``passes''
the recognized
token to the higher level parser
together with its interpreted value.  The interpreted
value of a terminal is determined by using the appropriate
interpretation function and the interpreted value of 
a keyword is simply its name (in upper case, if the
grammer is not case sensitive).  For example the <code> LispG</code>
lexical analyser recognizes <code> '('</code> as a keyword with the
value <code> '('</code> and <code> "this"</code> as an instance of the nonterminal
<code> str</code> with the value <code> 'this'</code>.
<p>
The higher level parser accepts tokens T from the lexical analyser
and does one of two things with them
<center><table bgcolor="#ffdd66" border>
<tr><td>
If the most recent
token values V the parser has saved on its ``tokens seen'' stack S
``looks like'' the body B of a
 rule R and the current token is a token that
could follow the nonterminal N at the head of R, then
the parser evaluates the reduction function F associated
with R, using the values V from the stack S that match the body
B together with the computational context C.  The resulting
value F(V,C) replaces the values V
</td></tr><tr><td>
Otherwise the current token is shifted onto the ``tokens seen''
stack S and the parser moves on to the next token.
</td></tr></table></center>
The above is a lie.
Actually, the parsing process is much smarter than this, but
from a users perspective this simplification may be 
helpful.
<p>
Figure Parse shows ``reduction'' steps and not
the ``shifts'', and glosses over the lexical analysis and
other nuances,
but it illustrates the idea of the parsing process nonetheless.
For example at step 2 the parse recognizes the last token
on the stack S
(an instance of the <code> "str"</code> terminal with value <code> "this"</code>)
as matching the body of <code> StrRule</code>, and replaces it
with the an instance of the nonterminal <code> Value</code>
with value determined by the reduction of <code> StrRule</code>.
In this case <code> StrRule</code> is associated with the reduction
function <code> EchoValue</code>, so the result of the reduction
is given by <code> EchoValue( 'this', C )</code> where C is the
context structure for the Parse.
<p>
At Step 3 the most recent entries of S 
<pre>
      V = ['(', 'SETQ', 'x', Value4, ')']
</pre>
match the body of the rule
<code> SetqRule</code>, so they are replaced on S by an instance
of the <code> Value</code> nonterminal with value determined by
<pre>
      Value3 = DoSet( V, C )
</pre>
Finally, at step 8, the interpretation associated
with <code> Value1</code> (an instance of the root nonterminal for
<code> LispG</code>) is  considered the result of the computation.

<h2>Parsing with a Grammar</h2>
<p>
Before you can perform a parse you probably must create a
computational context for the parse.  In the case of <code> LispG</code>
the context is simply a dictionary so we may initialize
<pre>
      Context = {}
</pre>
To create a context for Parsing.
<p>
There are two methods which provide the primary interfaces for
the parsing process for a grammar.
<pre>
      RESULT = GRAMMAROBJECT.Parse1(STRING, CONTEXT)
      (RESULT, CONTEXT) = GRAMMAROBJECT.Parse(STRING, CONTEXT)
</pre>
The second allows you to make explicit in code that uses parsing
the possibility that a parse may alter the context of the parse
-- aside from that the two functions are identical.  Example
usage for <code> Parse1</code> using <code> LispG</code> were given earlier.

<h2>Storing and Reloading a Grammar Object</h2>
<p>
The process of compiling a grammar may take significant time
and consume significant quantities of 
memory.  To
free up memory from structures in a 
compilable grammar object that aren't
needed after compilation use <code> GRAMMAR.CleanUp()</code>.
<p>
Once you have
debugged the syntax and semantics of your grammar you may
store syntactic information for the
grammar using the <code> Reconstruct</code>
method already mentioned.  The declarations created by <code>
Reconstruct</code> only defines the syntax for the grammar.
The semantics must be rebound separately.  But it is much better to
use UnMarshalGram as shown below, which stores the grammar
in a binary format.
<p>
For example, lines 12 through 14 of 
Figure GrammarBuild create a file <code> TESTLispG.py</code>
containing a function <code> GRAMMAR()</code> which will reconstruct
the syntax for the <code> LispG</code> grammar.


<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
        # from DLispShort.py

def unMarshalLispG():
    import kjParser
    infile = open("TESTLispG.mar", "r")
    LispG = kjParser.UnMarshalGram(infile)
    infile.close()
    DeclareTerminals(LispG)
    BindRules(LispG)
    return LispG
</pre>
This function can then be used in another file,
provided <code>DLispShort.GrammarBuild()</code> has been executed
at some point in the past, thusly:
<pre>
        import DLispShort
        LGrammar = DLispShort.unMarshalLispG()
</pre>
</td></tr>
<caption>Loading a precomputed grammar object.</caption>
</table></center>
<p>
Figure Load shows a function <code> LoadLispG</code>
that reloads the syntactic
portion of <code> LispG</code> from <code> TESTLispG.mar</code>.  
To rebind the semantics as well the
function re-declares the terminals and re-binds the rules
to make the reconstructed <code> LispG</code> suitable for use in parsing.

<h2>Errors raised</h2>
<p>
You may see the following errors:
<center><table bgcolor="#ffdd66" border>
<tr><th> LexTokenError</th></tr><tr><td>
This usually means the lowest level of the parser ran into a string
it couldn't recognize.
</td></tr><tr><th> BadPunctError</th></tr><tr><td>
You tried to make a whitespace character a punctuation.  
This is not currently allowed.
</td></tr><tr><th> EOFError, SyntaxError</th></tr><tr><td>
You tried to parse a string that is not valid for the grammar.
</td></tr><tr><th> TokenError</th></tr><tr><td>
During parser generation you used a string in the rule definitions
that wasn't previously registered as a terminal, nonterminal, or
punctuation.
</td></tr><tr><th> NotSLRError</th></tr><tr><td>
You attempted to build a grammar that is not ``SLR'' according
to the definition of Aho and Ullman.  Either the grammar is
ambiguous, or it doesn't have a derivation for the root
nonterminal, or it is too tricky for the generator.
</td></tr></table></center>
Furthermore
<code> NondetError, ReductError, FlowError, ParseInitError,
UnkTermError</code>
or errors raised by other modules
shouldn't happen.
If an error that shouldn't happen happens there are
two possibilities (1) you have fiddled with the code or
data structures and you broke something, or (2) there
is a serious bug in the module.

<h2>Possible Gotchas</h2>
<p>
This package has a number of known deficiencies, and there
are probably many that are yet to be discovered.
<p>
Syntax errors are not reported nicely.  Sorry.
<p>
Currently, there is no way to to resolve grammar
ambiguities.  For example a C construct
<pre>
if (x)
   if (y)
      x = 0;
   else
      y = 1;
</pre>
could have the <code> else</code> associated with either the
first or second if; the grammar doesn't indicate which.  
This is normally resolved by informing
the parser generator to prefer one binding or the other.
No method for providing a preference is implemented here, yet.
Let me know if you need such a method or if you have any suggestions.
<p>
Keywords of the meta-grammar cannot name tokens of
the object grammar (see footnote above).
<p>
If you want keywords to be recognized without case
sensitivity you must declare <code> G.SetCaseSensitivity(0)</code>
before any keyword declarations.
<p>
Name and regular expression collisions are not always
checked and reported.  If you name two rules the same,
for example, you may get undefined behavior.
<p>
The lexical analysis implementation is not as fast as it
could be (of course).
It also sees all white space as a
`single space'
so, for example, if indentation is significant in your grammar
(as in Python) you'll need a different lexical analyzer.
Also if <code> x=+y</code> means something different from 
<code> x = + y</code> (as it did in the original C, I believe)
you may have trouble.  Happily the lexical component can
be easily ``plug replaced'' by another implementation if needed.
<p>
Also, the system currently only handles SLR grammars (as defined
by Aho and Ullman), as mentioned above.  If you get a
<code> NonSLRError</code> during grammar compilation you need a better
parser generator.  I may provide one, if I have motivation and time.
<p>
I know of no outright bugs.  Trust me, they're there.  Please
find them for me and tell me about them.  I'm not a big
expert on parsing so I'm sure I've made some errors, particularly
at the lexical level.

<h2>Further Reading</h2>
<p>
A standard reference for parsing and compiler, interpreter,
and translator implementation is Principles of Compiler
Design, by Aho and Ullman (Addison Wesley).


<p>
<a href="mailto:arw@ifu.net">feedback</a><br>
<a href="../index.html">home</a><br>
<a href="index.html">Gadfly home</a>
</body>
</html>